package com.z_talk.client.view;

import com.z_talk.client.core.ClientSender;
import com.z_talk.client.localization.TalkLocalzation;
import com.z_talk.core.enums.RequestEnum;
import com.z_talk.core.message.RequestMessage;
import com.z_talk.core.model.PrivateTalkModel;
import com.z_talk.core.model.UserInfo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

public class PrivateTalkView {
    private JTextArea messageConsole;
    private JTextArea message;
    private JButton sendBut;
    private JPanel privateTalkPanel;

    UserInfo from;
    UserInfo to;
    private static ClientSender clientSender;

    public PrivateTalkView(UserInfo from,UserInfo to) {
        clientSender = ClientSender.getInstance();
        this.from = from;
        this.to = to;
        init();
    }

    private void init() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        JFrame jFrame = new JFrame(to.getNickName()+"("+to.getUserId()+")");
        jFrame.setContentPane(this.privateTalkPanel);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        jFrame.setSize(800,600);
        int x = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int y = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        jFrame.setLocation((x - jFrame.getWidth()) / 2, (y-jFrame.getHeight())/ 2);

        messageConsole.append(TalkLocalzation.loadPrivateTalk(from,to));

        message.requestFocus();

        sendBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RequestMessage requestMessage = new RequestMessage();
                requestMessage.setMessageType(RequestEnum.PRIVATE_TALK_REQUEST);
                Map<String, Object> modelMap = new HashMap<>();
                PrivateTalkModel privateTalkModel = new PrivateTalkModel();
                String talkMessage = message.getText();
                privateTalkModel.setMessage(talkMessage);
                privateTalkModel.setUserInfo(to);
                modelMap.put(RequestEnum.PRIVATE_TALK_REQUEST.getAttr(),privateTalkModel);
                requestMessage.setAttribute(modelMap);
                try {
                    clientSender.sendMsg(requestMessage);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }finally {
                    message.setText("");
                    message.requestFocus();
                }
            }
        });
    }

    // 更新消息显示
    public void updateMessage(String msg){
        TalkLocalzation.savePrivateTalk(from,to,msg);
        messageConsole.append(msg);
    }
}
